package com.xwb.controller;

import com.xwb.utils.RedisUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Array;

@Controller
public class FileController {
    /**
     * 单文件上传
     *
     */
    @RequestMapping("/upload")
    @RequiresRoles("0")
    @ResponseBody
    public  String uploadFile(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) {
        //判断文件是否为空
        if (multipartFile.isEmpty()) {
            return "File is not Empty!!";
        }
        //获取文件名
        String filename = multipartFile.getOriginalFilename();
        System.out.println("文件名:"+filename);
        //获取文件后缀名，进行判断选择要上传的文件类型
        String suffixName = filename.substring(filename.lastIndexOf("."));
        System.out.println("后缀名:"+suffixName);
        //设置存放根路径，可以设置任意存放位置，这里默认存放服务端根目录
//        String contextPath = request.getServletContext().getRealPath("/res/imgs/");
//        System.out.println(contextPath);
//        File file=new File(contextPath);
//        if (!file.exists()) {
//            file.mkdirs();
//        }
        //存放数据
        //File targetFile = new File(contextPath + filename);
        File targetFile = new File("C:/Users/43190/Desktop/"+filename);
        String contextPath="C:/Users/43190/Desktop/";
        //把文件路径存放在缓存中
        RedisUtils.redisTemplate.opsForValue().set("file",contextPath + filename);
        try {
            multipartFile.transferTo(targetFile);
            return "Success !!!";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "Failure !!!";

    }

    /**
     * 文件下载
     */
    @RequestMapping("/downLoad")
    @ResponseBody
    @RequiresRoles("0")
    public  String downLoad(HttpServletResponse response) throws UnsupportedEncodingException {
//        String filename="2.xlsx";
//        String filePath = "D:/download" ;
        File file = new File((String) RedisUtils.redisTemplate.opsForValue().get("file"));
        String filename = file.getName();
        if(file.exists()){ //判断文件父目录是否存在
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" +   java.net.URLEncoder.encode(filename,"UTF-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;
            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer,0,i);
                    os.flush();
                    i = bis.read(buffer);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("----------file download---" + filename);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "Success !!";

    }

}
